import React, { Component } from 'react';
import axios from 'axios';
import moment from 'moment';
import PropTypes from 'prop-types';
import { Icon } from 'antd';
import { connect } from 'react-redux';
import * as ACTION_TYPE from '../../store/constant';
import './style.less';

class ArticleDetail extends Component {
	static get propTypes() {
		return {
			article: PropTypes.object,
			articleList: PropTypes.array,
			match: PropTypes.object,
			changeArticle: PropTypes.func,
			getArticle: PropTypes.func
		};
	}
	render() {
		const { article } = this.props;
		return (
			<div className="articleDetail">
				<div className="title">{article.title}</div>
				<div className="author">
					<span>{moment(article.created_at).format('YYYY-MM-DD HH:mm:ss')}</span>
					<span className="count">
						<Icon type="eye-o" />
						{article.lookCount}
					</span>
				</div>
				<div className="content" dangerouslySetInnerHTML={{ __html: article.content}}></div>
			</div>
		);
	}
	UNSAFE_componentWillMount() {
		const { articleList, match, changeArticle, getArticle } = this.props;
		if (articleList.length > 0) {
			const articles = articleList.filter(item => item._id === match.params.id);
			changeArticle(articles[0]);
		}
		getArticle(match.params.id);
	}

	componentDidMount() {
		document.documentElement.scrollTop = 0;
	}
}

const mapState = state => {
	return {
		article: state.article,
		articleList: state.articleList
	};
};

const mapDispatch = (dispatch) => ({
	getArticle: id => {
		axios.get('https://api.justdodo.cn/acticles/' + id).then(res => {
			if (res && res.data.code === 1) {
				dispatch({
					type: ACTION_TYPE.ARTICLE,
					value: res.data.data
				});
			}
		});
	},
	changeArticle: article => {
		dispatch({
			type: ACTION_TYPE.ARTICLE,
			value: article
		});
	}
});

export default connect(
	mapState,
	mapDispatch
)(ArticleDetail);
